<script setup lang="ts">

import Footer from "../views/footer.vue";
import userAvatar from "../assets/tx.jpg";
import aiAvatar from "../assets/tx.jpg";

import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'


interface Message {
  role: 'user' | 'assistant'
  content: string
}

const messages = ref<Message[]>([])
const inputMessage = ref('')
const loading = ref(false)
const chatBox = ref<HTMLElement | null>(null)

// 修改配置部分
const AI_CONFIG = {
  baseURL: 'https://api.moonshot.cn/v1',
  apiKey: import.meta.env.VITE_MOONSHOT_API_KEY,
  model: import.meta.env.VITE_MOONSHOT_MODEL
}

// 创建OpenAI客户端
const client = {
  async chat(messages: any[], onContent: (content: string) => void) {
    try {
      const response = await fetch(`${AI_CONFIG.baseURL}/chat/completions`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${AI_CONFIG.apiKey}`
        },
        body: JSON.stringify({
          model: AI_CONFIG.model,
          messages: messages,
          temperature: 0.3,
          stream: true
        })
      })

      if (!response.ok) {
        throw new Error('Network response was not ok')
      }

      const reader = response.body?.getReader()
      const decoder = new TextDecoder()

      while (true && reader) {
        const { done, value } = await reader.read()
        if (done) break

        const chunk = decoder.decode(value)
        const lines = chunk.split('\n')

        for (const line of lines) {
          if (line.startsWith('data: ')) {
            const data = line.slice(6)
            if (data === '[DONE]') continue

            try {
              const json = JSON.parse(data)
              const content = json.choices[0].delta.content
              if (content) {
                onContent(content)
              }
            } catch (e) {
              console.error('Parse chunk failed:', e)
            }
          }
        }
      }
    } catch (error) {
      console.error('Chat failed:', error)
      throw error
    }
  }
}

// 格式化消息内容，将换行符转换为<br>
const formatMessage = (content: string) => {
  return content.replace(/\n/g, '<br>')
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatBox.value) {
    chatBox.value.scrollTop = chatBox.value.scrollHeight
  }
}

// 修改发送消息的处理函数
const handleSend = async () => {
  const message = inputMessage.value.trim()
  if (!message) {
    ElMessage.warning('请输入内容')
    return
  }

  // 添加用户消息
  messages.value.push({
    role: 'user',
    content: message
  })

  // 清空输入框并滚动到底部
  inputMessage.value = ''
  await scrollToBottom()

  // 发送消息
  loading.value = true
  try {
    // 构建消息历史
    const chatMessages = [
      {
        role: 'system',
        content: '你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。'
      },
      ...messages.value
    ]

    let responseContent = ''

    // 处理流式响应
    await client.chat(chatMessages, (content) => {
      responseContent += content

      // 更新或添加AI回复
      const lastMessage = messages.value[messages.value.length - 1]
      if (lastMessage.role === 'assistant') {
        lastMessage.content = responseContent
      } else {
        messages.value.push({
          role: 'assistant',
          content: responseContent
        })
      }

      scrollToBottom()
    })

  } catch (error: any) {
    console.error('发送消息失败:', error)
    ElMessage.error(error.message || '发送消息失败，请重试')
  } finally {
    loading.value = false
  }
}

// 初始欢迎语
onMounted(() => {
  messages.value.push({
    role: 'assistant',
    content: '你好！我是 Kimi，由 Moonshot AI 提供的人工智能助手。我可以回答您的各种问题，请问有什么可以帮助您的吗？'
  })
})

// 移除不需要的清理代码
onUnmounted(() => {
  // 不再需要清理WebSocket相关资源
})
</script>

<template>
  <div class="chat-container">
    <div class="chat-box" ref="chatBox">
      <div v-for="(message, index) in messages" :key="index"
           :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
        <div class="message-content">
          <div class="avatar">
            <img :src="message.role === 'user' ? userAvatar : aiAvatar"
                 :alt="message.role">
          </div>
          <div class="text">
            <div class="name">{{ message.role === 'user' ? '我' : 'AI助手' }}</div>
            <div class="content" v-html="formatMessage(message.content)"></div>
          </div>
        </div>
      </div>

      <!-- 加载动画 -->
      <div v-if="loading" class="message ai-message">
        <div class="message-content">
          <div class="avatar">
            <img :src="aiAvatar" alt="AI">
          </div>
          <div class="text">
            <div class="name">AI助手</div>
            <div class="typing-indicator">
              <span></span>
              <span></span>
              <span></span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="input-area">
      <el-input
          v-model="inputMessage"
          type="textarea"
          :rows="3"
          :disabled="loading"
          placeholder="请输入您的问题..."
          @keyup.enter.native.exact="handleSend"
      />
      <el-button
          type="primary"
          :loading="loading"
          :disabled="!inputMessage.trim()"
          @click="handleSend"
      >发送</el-button>
    </div>
  </div>
  <Footer></Footer>
</template>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.message {
  margin-bottom: 20px;
}

.message-content {
  display: flex;
  gap: 12px;
  max-width: 80%;
}

.user-message {
  display: flex;
  justify-content: flex-end;
}

.user-message .message-content {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.text {
  background: #f5f5f5;
  padding: 12px;
  border-radius: 8px;
  position: relative;
}

.user-message .text {
  background: #e8f5e9;
}

.name {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.content {
  font-size: 16px;
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-word;
}

.input-area {
  display: flex;
  gap: 12px;
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.input-area :deep(.el-textarea__inner) {
  resize: none;
  font-size: 16px;
  padding: 12px;
  line-height: 1.6;
}

.input-area :deep(.el-textarea__inner:disabled) {
  background-color: #f5f7fa;
  cursor: not-allowed;
}

.input-area .el-button {
  height: 100px;
  width: 100px;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.input-area .el-button:disabled {
  cursor: not-allowed;
}

/* 添加字动画样式 */
.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background-color: #2c5f2d;
  border-radius: 50%;
  animation: typing 1s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.4s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.6s;
}

@keyframes typing {
  0%, 100% {
    transform: scale(1);
    opacity: 0.3;
  }
  50% {
    transform: scale(1.2);
    opacity: 1;
  }
}


</style>
